package org.example.back.service.healthassistant;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Service
public class HealthAssistantService {

    private static final String API_URL = "https://maas-cn-southwest-2.modelarts-maas.com/v1/infers/271c9332-4aa6-4ff5-95b3-0cf8bd94c394/v1/chat/completions";
    private static final String API_KEY = "T1HZXwlr-svYUTKvSQFu_lkzKFpqGJgIh7m9Dh0sYvF_jUMsayG5BZWavC5QJjy2SnncOtB27E4wAFSZkvEXnQ";

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    public String getAnswerFromLLM(String question) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(API_KEY);

        // 构造请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "DeepSeek-V3");
        requestBody.put("stream", false); // 非流式
        requestBody.put("temperature", 0.6);

        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(Map.of("role", "system", "content", "你是一个健康生活应用的智慧问答助手，请根据用户提问给予科学、专业、友善的回答"));
        messages.add(Map.of("role", "user", "content", question));
        requestBody.put("messages", messages);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(API_URL, request, String.class);
            if (response.getStatusCode() == HttpStatus.OK) {
                JsonNode root = objectMapper.readTree(response.getBody());
                return root.path("choices").get(0).path("message").path("content").asText();
            } else {
                return "模型调用失败，状态码: " + response.getStatusCode();
            }
        } catch (Exception e) {
            return "调用模型出错：" + e.getMessage();
        }
    }
}
